import grp

import aiofiles
import falcon
import pwd

from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.store.ConfigurationStore import ConfigurationStore


@falcon.before(login_require)
class UserAPI:
    def __init__(self, cs: ConfigurationStore = None):
        self.config_store = cs

    async def on_get(self, req: falcon.request, resp: falcon.Response):
        type = req.params.get('type')
        if type is None:
            raise falcon.HTTPBadRequest(title='请求参数错误：name丢失')
        #############################################
        if type == 'local':
            login_users: list[dict] = []
            invalid_shells = {'/sbin/nologin', '/bin/false', '/usr/sbin/nologin', '/bin/sync', '/bin/true'}
            for user in pwd.getpwall():
                # 检查 shell 是否有效（不在无效列表里）
                if user.pw_shell not in invalid_shells:
                    # 获取用户组名（由 GID 转换）
                    try:
                        group_name = grp.getgrgid(user.pw_gid).gr_name
                    except KeyError:
                        group_name = str(user.pw_gid)  # 如果组名不存在，返回 GID
                    login_users.append({
                        "username": user.pw_name,
                        'uid': user.pw_uid,
                        'home': user.pw_dir,
                        "group": group_name,
                        "shell": user.pw_shell
                    })
            resp.media = login_users
        elif type == 'virtual':
            resp.media = []

        else:
            raise falcon.HTTPBadRequest(title='请求参数错误：type')
